﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.DataModel;
using Dict.Blo;
using ProtoBuf.Message;

namespace UI
{
    public class MineTab : MonoBehaviour
    {
        public UIScrollView scrollView;
        public SimpleGrid simpleGrid;
        public ArrayPage arrayPage;
        public GameObject emptyPrefab;
        public GameObject draggingRoot;

        string lastChosedId = "";
        Dictionary<string, MineIcon> mineIcons = new Dictionary<string, MineIcon>();

        GameObject MineIconPref
        {
            get
            {
                if (mineIconPref == null)
                    mineIconPref = AssetLoad.ResourceManager.Instance.LoadResource("prefab/MineIcon") as GameObject;
                return mineIconPref;
            }
        }

        GameObject mineIconPref;

        public void UpdateScrollView()
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            mineIcons.Clear();

            GameObject obj = AssetLoad.ResourceManager.Instance.LoadResource("prefab/MineIcon") as GameObject;
            int count = 0;
            List<UIMineItem> list = StaticData.playerData.GetMineItemsForArray();
            foreach (var mine in list)
            {
                GameObject icon = Instantiate(obj);
                simpleGrid.AddChild(icon);
                icon.AddComponent<UIDragScrollView>().scrollView = scrollView;

                MineDragDropItem dragdropitem = icon.AddComponent<MineDragDropItem>();
                dragdropitem.cloneOnDrag = true;
                dragdropitem.restriction = UIDragDropItem.Restriction.None;
                dragdropitem.m_callback = OnDragEnd;
                dragdropitem.m_startDragCallback = OnIconDragStart;
                
                MineIcon mineicon = icon.GetComponent<MineIcon>();
                mineicon.UpdateCount(mine.num.ToString(), UIWidget.Pivot.Right);
                mineicon.SetMine(mine.mineData.MineItemID);
                mineicon.m_callback = OnMineIconClick;
                icon.transform.localScale = new Vector3(0.9f, 0.9f, 0.9f);
                icon.SetActive(true);
                count++;
                mineIcons[mine.mineData.MineItemID] = mineicon;
            }

            int pagecount = 16;
            if (count > pagecount && count % 4 != 0)
                pagecount = count + 4 - count % 4;

            for (int i = count; i < pagecount; i++)
            {
                GameObject icon = Instantiate(emptyPrefab);
                Destroy(icon.GetComponent<BoxCollider>());
                simpleGrid.AddChild(icon);
                icon.transform.localScale = new Vector3(0.9f, 0.9f, 0.9f);
                icon.SetActive(true);
            }

            scrollView.ResetPosition();
        }


        void OnDragEnd(GameObject obj1)
        {
            GameObject draggingObj = obj1;
            int limit = 40;
            string id = draggingObj.GetComponent<MineIcon>().MineId;

            draggingObj.transform.parent = draggingRoot.transform;
            Vector3 pos = draggingObj.transform.localPosition;
            for (int i = 0; i < 4; i++)
            {
                Vector3 p = arrayPage.equipPositons[i].transform.localPosition;
                float dx = pos.x - p.x;
                float dy = pos.y - p.y;
                if (arrayPage.equipPositons[i].M_EquipIcon != null)
                {
                    arrayPage.equipPositons[i].M_EquipIcon.chosedBg.SetActive(false);
                    if (Mathf.Abs(dx) < limit && Mathf.Abs(dy) < limit)
                    {
                        bool check = CheckEquipPositionFit(i, id, true);
                        if (check)
                        {
                            CSGemMountOrChange msg = new CSGemMountOrChange();
                            msg.gemId = id;
                            msg.guid = arrayPage.equipPositons[i].M_EquipIcon.m_equip.guid;

                            NetAPI.SendHttp(OpDefine.CSGemMountOrChange, msg, (obj, suc) =>
                            {
                                if (suc)
                                {
                                    SCGemMountOrChange rmsg = obj.kBody as SCGemMountOrChange;
                                    StaticData.playerData.UpdateEquipment(rmsg.equip);
                                    StaticData.playerData.Delete(rmsg.cost);
                                    StaticData.playerData.AddResultObj(rmsg.res);

                                    arrayPage.OnArrayPosClick(arrayPage.CurPosition);
                                }
                            });
                        }
                    }
                }
            }

            Destroy(draggingObj);

            //取消装备位置变亮
            for (int i = 0; i < 4; i++)
            {
                if (arrayPage.equipPositons[i].M_EquipIcon != null)
                {
                    arrayPage.equipPositons[i].M_EquipIcon.chosedBg.SetActive(false);
                }
            }
        }

        void OnIconDragStart(GameObject obj)
        {
            if (obj != null)
            {
                //能镶嵌的装备位置变亮
                for (int i = 0; i < 4; i++)
                {
                    if (arrayPage.equipPositons[i].M_EquipIcon != null)
                    {
                        bool check = CheckEquipPositionFit(i, obj.GetComponent<MineIcon>().MineId);
                        arrayPage.equipPositons[i].M_EquipIcon.chosedBg.SetActive(check);
                    }
                }
            }
        }
        
        void OnMineIconClick(string id)
        {
            if (mineIcons.ContainsKey(lastChosedId))
                mineIcons[lastChosedId].chosedImg.SetActive(false);
            mineIcons[id].chosedImg.SetActive(true);

            lastChosedId = id;

            PageManager.instance.OpenPage("GemDetailPage", "id=" + id + "&place=0");
        }

        /// <summary>
        /// 阵容装备位置上的装备是否可镶嵌当前拖动的宝石
        /// </summary>
        /// <returns></returns>
        bool CheckEquipPositionFit(int index,string id, bool withTip = false)
        {
            EquipIcon icon = arrayPage.equipPositons[index].M_EquipIcon;
            if(icon != null)
            {
                TableMineSkill minedata = DictMineBlo.GetTableMineSkill(id);
                if(minedata.Color == 7 && (icon.m_equip.equipData.hole1 != 0 || icon.m_equip.equipData.hole2 != 0 || icon.m_equip.equipData.hole3 != 0 || icon.m_equip.equipData.hole4 != 0))
                    return true;
                if (icon.m_equip.equipData.hole1 == minedata.Color)
                    return true;
                if (icon.m_equip.equipData.hole2 == minedata.Color)
                    return true;
                if (icon.m_equip.equipData.hole3 == minedata.Color)
                    return true;
                if (icon.m_equip.equipData.hole4 == minedata.Color)
                    return true;

                if (withTip && icon.m_equip.equipData.quality <= (int)QualityValue.GREEN)
                {
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("gem_set_tip_1"));
                    return false;
                }
                
                if (withTip)
                {
                    string colorword = TableTextBlo.GetText("gem_color_" + minedata.Color.ToString());
                    BoxManager.CreatePopupTextBox(string.Format(TableTextBlo.GetText("gem_set_tip_2"), colorword, colorword));
                }

            }
            return false;
        }
    }
}

